<?php
namespace App\Repos;
use App\Models\Cate;
use App\Models\Product;
use App\Models\ProductImg;

use App\Models\ProductCar;

use App\Models\AdminHandlerLog;
use Carbon\Carbon;
use DB;
use App\Events\AdminHanderEvent;

class ProductRepo 
{
    
    public static function create($data)
    {
        $rs['status'] = false;
        try {
            DB::transaction(function () use ($data) {
                $pics = explode(',',rtrim($data['pics'],','));

                $productData = array_only($data,['name','cate_id','price','market_price']);
                $productData['code'] = 'C1'.date('YmdHis');
                if($data['cate_id'] == 2) {
                    $productData['code'] = 'C2'.date('YmdHis');
                }
                if($pics) $productData['thumb'] = $pics[0];
                $product = Product::create($productData);
                
                if($pics) {
                    
                    foreach ($pics as $k => $productImg) {
                        $img['imgurl']     = $productImg;
                        $img['product_id'] = $product->id;
                        ProductImg::create($img);
                    }    
                }

                if($data['car_brand_id']) {
                    foreach ($data['car_brand_id'] as $k => $v) {
                        $car['product_id'] = $product->id;
                        $car['brand_id']   = $v;
                        $car['serie_id']   = $data['car_serie_id'][$k];
                        $car['num']        = $data['num'][$k];
                        $car['is_headcar'] = $data['is_headcar'][$k];
                        ProductCar::create($car);
                    }
                }
                   


               
                
            });
            $rs['status'] = true;    
            return $rs;
               
            
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        $rs['status'] = true;
        return $rs;
    } 

    public static function update($id,$data,$tags=[],$pics=[],$group=[])
    {
        $rs['status'] = false;
        try {
            DB::transaction(function () use ($id,$data,$tags,$pics,$group) {
               
              
                $product = Product::where(['id'=>$id])->update($data);
                $where['product_id'] = $id;
                ProductImg::where($where)->delete();
                ProductTagRel::where($where)->delete();
                ProductGroup::where($where)->delete();

                if($pics) {
                    foreach ($pics as $k => $productImg) {
                        $img['imgurl'] = $productImg;
                        $img['product_id'] = $id;
                        ProductImg::create($img);
                    }    
                }

                if($tags) {
                    foreach ($tags as $tag) {
                        $t['tag_id'] = $tag;
                        $t['product_id'] = $id;
                        ProductTagRel::create($t);
                    }
                }

                if($group) {
                    $group['product_id'] = $id;
                    ProductGroup::create($group);
                }
                
            });
            $rs['status'] = true;    
            return $rs;
            
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();
            return $rs;
        }
        $rs['status'] = true;
        return $rs;
    }   
  

    public static function getListPages($where=[],$num=20,$fields=['*']) 
    {
    	$query = Product::query();        
        if(array_key_exists('name', $where) ) {           
            $query->where('name','like','%'.$where['name'].'%');
            unset($where['name']);
        }
        
        $query->with('imgs:id,product_id,imgurl');
      
        
        $query = $query->select($fields)->where($where);
        $list  = $query->orderBy('created_at','asc')
        					->paginate($num);
        return $list;					
    }

    public static  function destroy($cate_id)
    {
        $rs['status'] = false;
        $productNum = Product::where('cate_id',$cate_id)->count();
        if($productNum>0) {
            $rs['msg'] = '分类下还有商品，所以不能删除';
            return $rs;
        }

        $flag = Cate::destroy($cate_id);
        if($flag) {
            $rs['status'] = true;
        }
        return $rs;


    }

    public static function getList($where,$num=6)
    {
        $list = Product::where($where)->select(['id','name','price','market_price'])->take($num)->get();

        foreach ($list as $key => $v) {
             $headcar = DB::table('product_cars as car')
             ->select(['b.name as brand_name','s.name as seire_name','car.num'])
             ->where(['car.product_id'=>$v->id,'car.is_headcar'=>1])
             ->leftJoin('car_brands as b','b.id','=','car.brand_id') 
             ->leftJoin('car_series as s','s.id','=','car.serie_id')   
             ->first(); 
             $list[$key]['headcar'] = $headcar;

             $flowcar = DB::table('product_cars as car')
             ->select(['b.name as brand_name','s.name as serie_name','car.num'])
             ->where(['car.product_id'=>$v->id,'car.is_headcar'=>2])
             ->leftJoin('car_brands as b','b.id','=','car.brand_id') 
             ->leftJoin('car_series as s','s.id','=','car.serie_id')   
             ->first();
              $list[$key]['flowcar'] = $flowcar;

            $imgs = ProductImg::select(['id','imgurl'])->where(['product_id'=>$v->id])->get(); 
            $list[$key]['imgs'] = $imgs; 
        }
        return $list;   
                    
    }

    public static function find($where,$fields= ['*'])
    {
        $data = Product::where($where)
                        ->first();
        $headcar = DB::table('product_cars as car')
             ->select(['b.name as brand_name','s.name as seire_name','car.num'])
             ->where(['car.product_id'=>$data->id,'car.is_headcar'=>1])
             ->leftJoin('car_brands as b','b.id','=','car.brand_id') 
             ->leftJoin('car_series as s','s.id','=','car.serie_id')   
             ->get();
        $data['headcar'] = $headcar;       
        $flowcar = DB::table('product_cars as car')
             ->select(['b.name as brand_name','s.name as seire_name','car.num'])
             ->where(['car.product_id'=>$data->id,'car.is_headcar'=>2])
             ->leftJoin('car_brands as b','b.id','=','car.brand_id') 
             ->leftJoin('car_series as s','s.id','=','car.serie_id')   
             ->get();      
        $data['flowcar'] = $flowcar;                

        return $data;
    }

   

    public static function imgs($product_id)
    {
        $where['product_id'] = $product_id;
        $fields = ['id','product_id','imgurl'];
        return ProductImg::where($where)->select($fields)->get();
    }

    

    

    
    public static function getAll()
    {
        return Product::get();
    }



    // 修改产品上下架状态
    public static function ChangeStatus($id,$data)
    {
        $updateData['on_sale'] = $data['status'];
        self::update(['id'=>$id],$updateData);
        AdminHandlerLogRepo::create('Product',$id,$data);
        //dd($adminHandlerLog);       
        //event(new AdminHanderEvent($adminHandlerLog));

    }
}
